<template>
    <el-dialog v-model="visible" :title="title" width="500px" >
        <el-form :model="formData" ref="formRef" :rules="rules" label-width="80px" v-loading="loading">
            <el-form-item label="岗位编码" prop="code">
                <el-input v-model="formData.code" placeholder="请输入岗位编码" />
            </el-form-item>
            <el-form-item label="岗位名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入岗位名称" />
            </el-form-item>
            <el-form-item label="备注">
                <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="addOrUpdate">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { addReq, updateReq } from '@/api/sys/post/index.js'

const visible = ref(false)

const formData = reactive({
    id: '',
    code: '',
    name: '',
    remark: '',
})

const rules = reactive({
    code: [{ required: true, message: '请输入岗位编码', trigger: 'blur' }],
    name: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
})

const props = defineProps({
    querySelective: Function,
})

const title = ref('')
const actionType = ref('')
const loading = ref(false)
const open = (type, row) => {
    if (type == 'add') {
        actionType.value = type
        title.value = '添加岗位'
        formData.code = ''
        formData.name = ''
        formData.remark = ''
        formRef.value?.resetFields()
        visible.value = true;
    }
    if (type == 'update') {
        actionType.value = type
        title.value = '修改岗位'
        formData.id = row.id
        formData.code = row.code
        formData.name = row.name
        formData.remark = row.remark
        visible.value = true;
    }

}

defineExpose({
    open
})


const close = () => {
    visible.value = false;
}

const formRef = ref()
const addOrUpdate = async () => {
    const valid = await formRef.value?.validate() // 改变这一行
    if (valid) {
        if (actionType.value == 'add') {
            const res = await addReq(formData);
            if (res.code == 200) {
                // 添加成功！
                ElMessage.success(res.message)
                // 查询列表
                props.querySelective();
                close();
            }
        }
        if (actionType.value == 'update') {
            const res = await updateReq(formData);
            if (res.code == 200) {
                // 添加成功！
                ElMessage.success(res.message)
                // 查询列表
                props.querySelective();
                close();
            }
        }
    }
}
</script>